<!--
 * @Author: your name
 * @Date: 2021-07-21 21:20:56
 * @LastEditTime: 2021-07-23 21:22:20
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Self\hm-news-86\src\views\login\index.vue
-->
<template>
  <div>
    <van-nav-bar title="登录" />
    <!-- 表单的submit事件在点击按钮,并且校验通过才触发 -->
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        label="手机号"
        placeholder="请输入手机号码"
        :rules="rules.mobile"
      />
      <!-- 字符串的false布尔类型还是true -->
      <van-field
        v-model="code"
        type="number"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
// import axios from 'axios'
// import axios from '@/utils/request'
import { userlogin } from '@/api/user'

export default {
  data() {
    return {
      mobile: '17987687212',
      code: '246810',
      // 手机号的校验规则
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ],
        // 验证码校验
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '验证码格式不正确' }
        ]
      },
      isLoading: false
    }
  },
  // 这里面不能利用按钮发送请求,因为表单校验不通过的时候也会触发
  methods: {
    async login() {
      // 这是原始写法,因为对axios进行了封装,所以直接导入request
      // const res = await axios({
      //   url: 'http://toutiao.itheima.net/v1_0/authorizations',
      //   method: 'POST',
      //   data: {
      //     mobile: this.mobile,
      //     code: this.code
      //   }
      // })
      // 这是用封装的axios写的
      // const res = await axios({
      //   url: '/v1_0/authorizations',
      //   method: 'POST',
      //   data: {
      //     mobile: this.mobile,
      //     code: this.code
      //   }
      // })
      // 这个是用封装的用户请求==>顺带设置loading效果,发请求时打开,请求完成关闭
      this.isLoading = true
      try {
        const res = await userlogin(this.mobile, this.code)
        console.log(res.data)
        this.$store.commit('user/setToken', res.data)
        this.$toast.success('登录成功')
      } catch {
        this.$toast.fail('登录失败')
      }
      this.isLoading = false
    }
  }
}
</script>
